# tests/conftest.py
from grpc import services
import logging
import pytest
import tomllib
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.remote.webdriver import WebDriver


# 移除 autouse=True，改为按需执行
@pytest.fixture(scope="session")
def setup_module(driver: WebDriver, base_url: str):
    # 跳转到指定的URL
    logging.info(f"开始测试")
    return

def teardown_module(driver: webdriver):
    # 在测试会话结束后关闭浏览器
    logging.info(f"结束测试")
    try:
        driver.quit()
    except:
        pass

# 移除 autouse=True，防止自动创建
@pytest.fixture(scope="function")
def driver(config: dict) -> WebDriver:
    driver = run_browser(config["browser_driver"]["driver"], config["browser_driver"]["driver_path"])
    try:
        yield driver
    finally:
        try:
            driver.quit()
        except:
            pass


@pytest.fixture(scope="session", autouse=True)
def config() -> dict:
    return load_config()

@pytest.fixture(scope="session", autouse=True)
def base_url(config) -> str:
    return "http://" + config["web_server"]["host"] + ":" + str(config["web_server"]["port"])

def load_config() -> dict:
    with open("config/application.toml", "rb") as f:
        config = tomllib.load(f)
    return config

def run_browser(browser_type: str, driver_path: str) -> WebDriver:
    # 启动浏览器的逻辑
    if browser_type == "chrome":
        logging.info(f"启动Chrome浏览器，驱动路径：{driver_path}")
        print(f"启动Chrome浏览器，驱动路径：{driver_path}")
        service = ChromeService(executable_path=driver_path)
        options = webdriver.ChromeOptions()
        options.add_argument("--no-sandbox")
        options.timeouts = {'script': 50000}
        options.timeouts = {'pageLoad': 50000}
        options.page_load_strategy = 'none'
        # 全屏启动
        options.add_argument("--start-maximized")

        # 移除detach选项，避免浏览器进程残留
        # options.add_experimental_option("detach", True)
        driver = webdriver.Chrome(service=service, options=options)
        # 启动后导航到空白页
        driver.get("about:blank")
        return driver
    elif browser_type == "edge":
        logging.info(f"启动Edge浏览器，驱动路径：{driver_path}")
        service = EdgeService(executable_path=driver_path)
        options = webdriver.EdgeOptions()
        driver = webdriver.Edge(service=service, options=options)
        driver.get("about:blank")
        return driver
        # 启动Edge浏览器的代码
        # 启动Edge浏览器的代码
    else:
        raise ValueError(f"不支持的浏览器类型: {browser_type}")
